package com.xiaoma.h5testdemo.common.helper

import android.app.Application
import android.content.Context
import android.content.MutableContextWrapper
import android.os.Looper
import android.os.SystemClock
import com.xiaoma.h5testdemo.common.widget.XmProxyChromeWebView
import com.xiaoma.lib.log.KLog
import java.util.*

/**
 * author: liangjingbo
 * date: 2022/8/16
 * describe:
 */
class WebViewCacheHolder private constructor() {
    private val mChromeWebViewCacheStack = Stack<XmProxyChromeWebView>()
    private lateinit var application: Application

    fun init(application: Application) {
        KLog.i(TAG, "init() ")
        this.application = application
        prepareWebView()
    }

    fun prepareWebView() {
        prepareChromeWebView()
    }

    fun acquireChromeWebViewInternal(context: Context): XmProxyChromeWebView {
        if (mChromeWebViewCacheStack.isEmpty()) {
            return createChromeWebView(context)
        }
        val webView = mChromeWebViewCacheStack.pop()
        val contextWrapper = webView.context as MutableContextWrapper
        contextWrapper.baseContext = context
        return webView
    }

    private fun prepareChromeWebView() {
        if (mChromeWebViewCacheStack.size < CACHE_WEB_VIEW_MAX_NUM) {
            Looper.getMainLooper().queue.addIdleHandler {
                if (mChromeWebViewCacheStack.size < CACHE_WEB_VIEW_MAX_NUM) {
                    val time1 = SystemClock.elapsedRealtime()
                    mChromeWebViewCacheStack.push(createChromeWebView(MutableContextWrapper(application)))
                    val time2 = SystemClock.elapsedRealtime()
                    KLog.i(TAG, "prepareChromeWebView() diff: ${time2 - time1}")
                }
                false
            }
        }
    }

    private fun createChromeWebView(context: Context): XmProxyChromeWebView {
        return XmProxyChromeWebView(MutableContextWrapper(context))
    }

    companion object {
        val INSTANCE: WebViewCacheHolder by lazy { WebViewCacheHolder() }
        private const val CACHE_WEB_VIEW_MAX_NUM = 1
        private const val TAG = "WebViewCacheHolder"
    }
}